package mqttclient

import (
	"emsctrl/devdata"
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"time"
)

const (
	REPORT_DATA_TOPIC = "/dev/report/colloc/data"
)

func MqttInit(broker string, port int) mqtt.Client {
	fmt.Println(broker, port)
	options := mqtt.NewClientOptions()
	options.AddBroker(fmt.Sprintf("mqtt://%s:%d", broker, port))
	clientId := "MqttCliend-" + time.Now().Format(time.DateTime)
	options.SetClientID(clientId)
	options.SetUsername("root")
	options.SetPassword("root")
	options.SetAutoReconnect(true)
	options.OnConnect = connectHandler
	options.OnConnectionLost = connectLostHandler
	options.SetDefaultPublishHandler(messagePubHandler)
	client := mqtt.NewClient(options)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}
	return client
}

var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
	fmt.Println("Connected Mqtt Server！！！")
	subscribe := client.Subscribe(REPORT_DATA_TOPIC, 1, submessageHandler)
	fmt.Println("subscribed to topic", "message_topic", subscribe)
}

var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
	fmt.Println("Connect lost:%v", err)
}

var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, message mqtt.Message) {
	fmt.Println("Received Message from topic:", message.Topic(), "message:", string(message.Payload()))
	client.Publish("/AAA/BBB/", 0, false, "AAAA BBB CCC")

}

var submessageHandler mqtt.MessageHandler = func(client mqtt.Client, message mqtt.Message) {
	//fmt.Println("Sub Received Message from topic:", message.Topic())
	//msg := ReportDataMsg{}
	//err := json.Unmarshal(message.Payload(), &msg)
	//if err != nil {
	//	return
	//}
	//fmt.Println(msg.DevName, msg.ParaType, msg.Data)
	devdata.DataAnalysis(message.Topic(), message.Payload())

}
